<template>
  <Table
    :data-source="logsList"
    :columns="columns"
    :style="{ height: '550px' }"
    :scroll="{ y: 700 }"
    :pagination="false"
  >
    <template #bodyCell="{ column, text, record }">
      <template v-if="column.dataIndex === 'operation'">
        <Space v-show="record.size > 1">
          <Button
            type="link"
            @click="handleViewLogs(record)"
            style="color: #6ad7ca"
            >预览</Button
          >
          <Button
            type="link"
            @click="handleLogsdown(record)"
            style="color: #6ad7ca"
            >下载</Button
          >
        </Space>
      </template>
    </template>
  </Table>
  <!-- 分页 -->
  <Pagination
    v-if="logsTotal > 0"
    :total="logsTotal"
    v-model:current="querylogsParams.pageNum"
    v-model:pageSize="querylogsParams.pageSize"
    :changeApi="handleCurrentChange"
  ></Pagination>
  <!-- 日志预览 -->
  <Modal
    title="日志预览"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
    v-model:open="visibleLog"
    width="40%"
  >
    <div class="card-container">
      <Textarea disabled :autoSize="true" v-model:value="historyLogText">
      </Textarea>
    </div>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { Button, Modal, Space, Table, Textarea, message } from 'ant-design-vue';
import minioClient from '@/plugins/minio';
import Pagination from '@/components/Pagination/Index.vue';
import { ProTableProps } from '@/components/ProTable/index';
import { Utf8ArrayToStr } from '@/utils/utils';

interface Props {
  pageData: any;
}
const props = defineProps<Props>();

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '日志大小',
    dataIndex: 'size',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
  },
]);

const getFileName = (url: string) => {
  // 通过最后一个斜杠将URL分割成数组
  let parts = url.split('/');
  // 获取数组中最后一个元素
  let fileName = parts[parts.length - 1];
  // 返回文件名
  return fileName;
};

// 获取日志列表
const getLogsList = () => {
  // 获取该bucket下的所有对象
  const objectsStream = minioClient.listObjects(
    'yjzd',
    props.pageData.code + '/Logs',
    true,
  );
  // 定义一个数组来保存所有对象路径
  objectsStream.on('data', (object: any) => {
    logsTotalList.value.unshift({
      name: getFileName(object.name as string),
      size: object.size,
    });
  });
  // 在流结束时输出所有对象的路径
  objectsStream.on('end', () => {
    handleCurrentChange();
  });
  // 遇到错误时输出错误信息
  objectsStream.on('error', (err: any) => {
    console.log(err);
  });
};
getLogsList();

interface ILogItem {
  name: string;
  size: any;
}
const logsTotal = ref(0);
const logsList = ref([]);
const logsTotalList = ref<Array<ILogItem>>([]);
const querylogsParams = ref({
  pageNum: 1,
  pageSize: 10,
});

const handleCurrentChange = () => {
  let _data: Array<ILogItem> = [];
  _data = logsTotalList.value.slice(
    (querylogsParams.value.pageNum - 1) * querylogsParams.value.pageSize,
    querylogsParams.value.pageNum * querylogsParams.value.pageSize,
  );
  logsTotal.value = logsTotalList.value.length;
  logsList.value = _data as any;
};

// 历史日志预览
const historyLogText = ref('');
const visibleLog = ref(false);
/**
 * 日志预览
 * @param record
 */
const handleViewLogs = (record: any) => {
  const backetName = 'yjzd';
  //  this.pageData.code + '/Logs/' + row.name 'BOEV10000001/Logs/2023-07-07.txt'
  minioClient.getObject(
    backetName,
    props.pageData.code + '/Logs/' + record.name,
    (err: any, dataStream: any) => {
      if (err) return message.error(err);
      const arr: Array<any> = [];
      let size = 0;
      dataStream.on('data', (chunk: any) => {
        if (chunk.length > 0) {
          // this.historyLogText =this.Utf8ArrayToStr(chunk)
          arr.push(chunk);
          size += chunk.length;
        }
      });
      dataStream.on('end', () => {
        const u8arr = new Uint8Array(size);
        let u8arrIndex = 0;
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr[i].length; j++) {
            u8arr[u8arrIndex] = arr[i][j];
            u8arrIndex += 1;
          }
        }
        historyLogText.value = Utf8ArrayToStr(u8arr);
        visibleLog.value = true;
      });
    },
  );
};

/**
 * 日志下载
 */
const handleLogsdown = (record: any) => {
  const backetName = 'yjzd';
  minioClient.getObject(
    backetName,
    props.pageData.code + '/Logs/' + record.name,
    (err: any, dataStream: any) => {
      if (err) return message.error(err);
      const arr: Array<any> = [];
      let size = 0;
      dataStream.on('data', (chunk: any) => {
        if (chunk.length > 0) {
          arr.push(chunk);
          size += chunk.length;
        }
      });
      dataStream.on('end', () => {
        const u8arr = new Uint8Array(size);
        let u8arrIndex = 0;
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr[i].length; j++) {
            u8arr[u8arrIndex] = arr[i][j];
            u8arrIndex += 1;
          }
        }
        const arrBuffer = u8arr.buffer;
        const blob = new Blob([arrBuffer]);
        const blobUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.setAttribute('href', blobUrl);
        a.setAttribute('download', record.name);
        a.click();
      });
      dataStream.on('error', (er: any) => {
        message.error(er);
      });
    },
  );
};
</script>

<style lang="scss" scoped></style>
